package main

import (
	"context"
	"fmt"
	"time"
)

const MqSendTimeout = time.Microsecond * 1500

func main() {
	// chan T // 可以接收和发送类型为T的数据
	//chan<- float64 //可以用来发送float64类型的数据
	context.WithCancel(context.Background())
	//for i := 0; i < 100000; i++ {
	//	time.Sleep(time.Duration(rand.Intn(6000))* time.Microsecond)
	timeTask(1)
	//timeTask2(1)
	//}
}

func timeTask(index int) {
	// 开启定时器，发送mq消息
	fmt.Println("index", index)
	err := mockErrr()

	stop := make(chan struct{}, 1)

	go func() {
		//time.Sleep(800 * time.Microsecond)
		err = refund()
		stop <- struct{}{}
	}()

	select {
	case <-stop:
		if nil != err {
			fmt.Println("执行退款异常了~~", err)
		} else {
			fmt.Println("执行退款逻辑成功~~~")
		}
	case <-time.After(time.Microsecond * 500):
		fmt.Println("超时~~~")
	}

	fmt.Println("我是最后要做的事情。。。。")
}
func timeTask2(index int) {
	// 开启定时器，发送mq消息
	ctx, cancel := context.WithTimeout(context.TODO(), MqSendTimeout)
	defer cancel()
	err := mockErrr()
	go func(ctx2 context.Context) {
		//time.Sleep(time.Duration(rand.Intn(6000)) * time.Microsecond)
		err = refund()
	}(ctx)

	select {
	case <-ctx.Done():
		if nil != err {
			fmt.Println("执行退款异常了~~", err)
		}
		fmt.Println("执行退款逻辑成功~~~")
		return
	case <-time.After(MqSendTimeout):
		fmt.Println("超时~~~")
		return
	}
	fmt.Println("我是最后要做的事情。。。。")
}

func mockErrr() error {
	return nil
}

func refund() error {
	fmt.Println("执行退款逻辑~~~")
	//time.Sleep(1000 * time.Microsecond)
	return fmt.Errorf("%s", "not found")
	//return nil
}
